//
//  SHPOAuthViewController.swift
//  weibo
//
//  Created by songhuipan on 16/4/18.
//  Copyright © 2016年 songhuipan. All rights reserved.
//

import UIKit

class SHPOAuthViewController: UIViewController {
    
    override func loadView() {
        
        view = webView
        
        webView.delegate = self
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoScanf")
        
        navigationItem.title = "登录微博"
    }

    override func viewDidLoad() {
        super.viewDidLoad()
                
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthUrl))
    }
    
    private lazy var webView :UIWebView = UIWebView()

}
extension SHPOAuthViewController :UIWebViewDelegate {
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if let urlString=request.URL?.absoluteString where urlString.hasPrefix(redirectUrl) {
            
            if let q = request.URL?.query {
                let code = q.substringFromIndex("code=".endIndex)
                
                SHPUserAccountViewModel.sharedUserAccount.getAccessToken(code, finished: { (isSuccessed) -> () in
                    isSuccessed == false ?print("出错了"):self.dimissAndPostNotification()
                })
                // 这里如果不return false 可能造成界面一直加载不出来，按照下面的写法
                return false

            }
        }
        
//        guard let urlString=request.URL?.absoluteString where urlString.hasPrefix(redirectUrl) else {
//            
//            return false
//        }
//        guard let _ = request.URL?.query else {
//            
//            return false
//        }
//        let code = request.URL!.query!.substringFromIndex("code=".endIndex)
//        // 根据code获得accessToken,同时加载用户数据，完成归档
//        SHPUserAccountViewModel.sharedUserAccount.getAccessToken(code, finished: { (isSuccessed) -> () in
//             isSuccessed == false ?print("出错了"):self.dimissAndPostNotification()
//                    })
        return true
    }
}
extension SHPOAuthViewController {
    // MARK:销毁控制器，发送通知改变根视图
    private func dimissAndPostNotification (){
        // 切换根视图之前先销毁控制器
        self.dismissViewControllerAnimated(false, completion: { () -> Void in
            
            // 发送通知改变根视图
         NSNotificationCenter.defaultCenter().postNotificationName("switchDefaultController", object: nil)
        })
    }
    // MARK:监听关闭按钮点击事件
    @objc private func dismiss () {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    // MARK:监听自动填充按钮点击事件
    @objc private func autoScanf () {

        let jsString = "document.getElementById('userId').value='\(weiboUserName)';document.getElementById('passwd').value='\(weiboPassWord)'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
}












